<template>
  <!-- 图形验证码 -->
  <canvas
    @click="randomCode"
    ref="codeCanvas"
    :width="contentWidth"
    :height="contentHeight"
  ></canvas>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const props = defineProps(['contentWidth', 'contentHeight'])
const codeCanvas = ref()
const emit = defineEmits(['changeCode'])
let identifyCode = ''
const backgroundColorMin = 180
const backgroundColorMax = 240
const fontSizeMin = 35
const fontSizeMax = 35
const colorMin = 50
const colorMax = 160
const lineColorMin = 100
const lineColorMax = 200
const randomNum = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min) + min)
}
const randomColor = (min: number, max: number) => {
  let r = randomNum(min, max)
  let g = randomNum(min, max)
  let b = randomNum(min, max)
  return 'rgb(' + r + ',' + g + ',' + b + ')'
}
const drawText = (ctx: CanvasRenderingContext2D, txt: string, i: number) => {
  ctx.fillStyle = randomColor(colorMin, colorMax)
  ctx.font = randomNum(fontSizeMin, fontSizeMax) + 'px serif'
  let x = (i + 1) * (props.contentWidth / (identifyCode.length + 1))
  let y = randomNum(fontSizeMax, props.contentHeight - 5)
  var deg = randomNum(-10, 10)
  // 修改坐标原点和旋转角度
  ctx.translate(x, y)
  ctx.rotate((deg * Math.PI) / 180)
  ctx.fillText(txt, 0, 0)
  // 恢复坐标原点和旋转角度
  ctx.rotate((-deg * Math.PI) / 180)
  ctx.translate(-x, -y)
}
// 绘制干扰线
const drawLine = (ctx: CanvasRenderingContext2D) => {
  for (let i = 0; i < 8; i++) {
    ctx.strokeStyle = randomColor(lineColorMin, lineColorMax)
    ctx.beginPath()
    ctx.moveTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
    ctx.lineTo(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight))
    ctx.stroke()
  }
}
const drawDot = (ctx: CanvasRenderingContext2D) => {
  // 绘制干扰点
  for (let i = 0; i < 100; i++) {
    ctx.fillStyle = randomColor(0, 255)
    ctx.beginPath()
    ctx.arc(randomNum(0, props.contentWidth), randomNum(0, props.contentHeight), 1, 0, 2 * Math.PI)
    ctx.fill()
  }
}
const drawPic = () => {
  let ctx = codeCanvas.value.getContext('2d') as CanvasRenderingContext2D
  ctx.textBaseline = 'bottom'
  // 绘制背景
  ctx.fillStyle = randomColor(backgroundColorMin, backgroundColorMax)
  ctx.fillStyle = 'rgb(255,255,255)'
  ctx.fillRect(0, 0, props.contentWidth, props.contentHeight)
  // 绘制文字
  for (let i = 0; i < identifyCode.length; i++) {
    drawText(ctx, identifyCode[i], i)
  }
  // 绘制背景
  drawLine(ctx)
  drawDot(ctx)
}
onMounted(() => {
  randomCode()
})
const randomCode = () => {
  identifyCode = randomNum(1000, 10000).toString()
  emit('changeCode', identifyCode)
  drawPic()
}
</script>
